<template>
  <div class="webchatHeadBox">
    <div class="title fl">
      <!-- 有客户名展示客户名，而且展示访客名 -->
      <span class="name">{{ webchatInfo.visitorName }}</span>
      <span
        class="V7_iconfont platform"
        :style="handleIsVistorBreakStyle(webchatInfo)"
        :class="handlePlatformIcon(webchatInfo)"
      ></span>
      <!-- 会话时长 -->
      <div
        class="webchatTime"
        v-if="['webchat_todo', 'webchat_close', 'webchat_queue'].includes(type)"
      >
        {{
          `${type === "webchat_queue" ? "进线等待时长" : "会话时长"}: ${timing}`
        }}
      </div>
    </div>
    <!-- 提交质检 -->
    <el-tooltip
      effect="dark"
      :content="getQtText()"
      placement="bottom"
      slot="reference"
    >
      <div v-if="getQtestingStatus === 'scored'" slot="content">
        {{ "质检分数:" + webchatInfo.gradeScore }}分<br />
        {{ "质检点评:" + webchatInfo.comments }}
      </div>
      <span
        @click="handleQualitytesting"
        v-functions="['im_session_commit_cancel_qc']"
        style="padding-top: 13px; margin-left: 20px; cursor: pointer"
        :class="['fr', 'V7_iconfont', getQtIcon()]"
      ></span>
    </el-tooltip>
    <!-- 关闭会话 -->
    <span
      v-if="['webchat_todo'].includes(type)"
      class="V7_iconfont V7_iconV7tubiao_tuichu fr"
      @click="closeWebchatSession"
    ></span>
    <!-- 转接会话 -->
    <el-popover
      v-model="isShowTransfer"
      popper-class="transferPopover v7-micro"
      ref="transferRef"
      placement="bottom"
      width="250"
      trigger="manual"
    >
      <webchatTransfer
        :peerAndOnlineAgents="peerAndOnlineAgents"
        @refreshTransfer="refreshTransfer"
        @transferPeer="transferPeerOrAgent"
        @transferAgent="transferPeerOrAgent"
      >
      </webchatTransfer>
      <el-tooltip
        v-show="['webchat_todo'].includes(type)"
        class="fr item"
        slot="reference"
        effect="dark"
        content="转接会话"
        placement="bottom"
      >
        <span
          :style="{ color: isShowTransfer ? '#008BEE' : '' }"
          class="transfer fr V7_iconfont V7_iconV7tubiao_zhuanchuhuihua"
          @click="transferFun()"
        ></span>
      </el-tooltip>
    </el-popover>
    <!-- 留言处理 -->
    <el-tooltip
      v-if="
        ['webchat_leaveMessage'].includes(type) && webchatInfo.status === 'deal'
      "
      class="fr item"
      slot="reference"
      effect="dark"
      content="标记为已处理"
      placement="bottom"
    >
      <span
        class="V7_iconfont V7_iconV7tubiao_yichuli"
        @click="dealLeaveMessage()"
      ></span>
    </el-tooltip>
    <span
      v-functions="['im_session_block']"
      v-if="['webchat_todo'].includes(type) && webchatInfo.platform !== 'wxsdk'"
      class="fr"
      style="margin-right: 20px; padding-top: 13px"
      ><BlackDialog :webchatInfo="webchatInfo"></BlackDialog
    ></span>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import { WebchatModule } from '@/store/modules/webchat'
import webchatTransfer from '@/views/webchat/common/webchatTransfer.vue'
import { PeerOrAgentObj, BreakStyleObj, PlatIcon } from '@/views/webchat/webchatInterface'
import { deepClone } from '@/utils/common'
import BlackDialog from './common/blackDialog.vue'
import { CommonModule } from '@/store/modules/common'
@Component({
  name: 'webchatContentBox',
  components: { webchatTransfer, BlackDialog }
})
export default class WebchatContentBox extends Vue {
  @Prop() private webchatInfo: any // 会话详情数据
  private $route: any
  private $confirm: any
  private $message: any
  private $bus: any
  private $store: any
  private isShowTransfer = false // 是否展示转接会话弹窗

  private timing: any = '00:00:00'

  private currentTime: number = 0

  private peerAndOnlineAgents = [] // 技能组数据

  private webchatTimer: any

  get type () {
    return this.$route.path.split('/')[3]
  }

  get diffTime () {
    return (CommonModule as any).diffTime
  }

  private handleIsVistorBreakStyle (obj: BreakStyleObj) {
    if (obj.isVisitorBreak) { // 访客离线
      return 'color: #CFD0D1'
    } else { // 访客在线
      switch (obj.platform) {
        case 'pc': // pc渠道
          return 'color: #F4A818'
        case 'wap': // wap、h5
          return 'color: #41ACF8'
        case 'weixin': // 微信
          return 'color: #7587D8'
        case 'wxmini': // 小程序
          return 'color: #7587D8'
        case 'sdk': // sdk
          return 'color: #1A91ED'
        case 'wxsdk': // 微信小程序sdk
          return 'color: #53C931'
        case 'wxwork': // 企业微信
          return 'color: #0082ef'
        case 'ocpc': // 百度bcp
          return 'color: #4581fb'
        case 'wxkf': // 微信客服
          return 'color: #5db069'
      }
    }
  }

  private handlePlatformIcon (obj: PlatIcon) { // 处理卡片访客来源icon图标
    switch (obj.platform) {
      case 'pc': // pc
        return 'V7_iconV7tubiao_qudao-wangzhan'
      case 'wap': // wap、h5
        return 'V7_iconV7tubiao_qudao-H5'
      case 'weixin': // 微信
        return 'V7_iconV7tubiao_weixingongzhonghao'
      case 'wxmini': // 小程序
        return 'V7_iconV7tubiao_weixinxiaochengxu'
      case 'sdk': // sdk
        return 'V7_iconV7tubiao_app'
      case 'wxsdk': // 微信小程序sdk
        return 'V7_iconV7tubiao_weixinxiaochengxu1'
      case 'wxwork': // 企业微信
        return 'V7_iconV7tubiao_qiyeweixin'
      case 'ocpc': // 百度bcp
        return 'V7_iconV7tubiao_baiduBCP'
      case 'wxkf': // 微信客服
        return 'V7_iconV7tubiao_weixinkefu'
    }
  }

  private closeWebchatSession () { // 结束会话事件
    this.$confirm('确定要结束会话吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const data = { finishData: [{ _id: this.webchatInfo._id, visitorId: this.webchatInfo.visitorId }] }
      const actionData = { url: '/im-center/action/webchat/finishWebchatSession', method: 'POST', data }
      WebchatModule.webchatCommonAction(actionData).then(res => {
        if (res) {
          WebchatModule.CLOSE_WEBCHAT_SESSION({ type: this.type, id: this.webchatInfo._id })
        }
      })
    })
  }

  private dealLeaveMessage () {
    const { _id, visitorId } = this.webchatInfo
    const actionData = { url: '/im-center/action/webchat/finishLeaveSession', method: 'POST', data: { sessionId: _id, visitorId } }
    WebchatModule.webchatCommonAction(actionData).then(res => {
      if (res) {
        WebchatModule.CLOSE_WEBCHAT_SESSION({ type: 'leave_todo', id: this.webchatInfo._id })
        this.$bus.$emit('dealLeaveMessage')
      }
    })
  }

  private transferPeerOrAgent (obj: PeerOrAgentObj) {
    const sendData: any = {
      sessionId: this.webchatInfo._id, // 会话id
      visitorId: this.webchatInfo.visitorId
    }
    if (obj.agentInfo) { // 转接座席
      sendData.peerId = obj.peerInfo.peerId // 座席所在技能组id
      sendData.peerName = obj.peerInfo.peerName // 座席所在技能组名
      sendData.agentId = obj.agentInfo.agentId // 转接座席id
    } else { // 转接技能组
      sendData.peerId = obj.peerId // 技能组id
      sendData.peerName = obj.peerName // 技能组名
    }
    const actionData = { url: '/im-center/action/webchat/redirectWebchatSession', method: 'POST', data: sendData }
    WebchatModule.webchatCommonAction(actionData).then(res => {
      if (res && res.success) {
        this.$message.success('转接成功')
        this.isShowTransfer = false
        WebchatModule.CLOSE_WEBCHAT_SESSION({ type: this.type, id: this.webchatInfo._id }) // 右侧清除会话
      }
    })
  }

  private transferPopFun (e: any) {
    const ref: any = this.$refs.transferRef
    if (ref && !ref.$el.contains(e.target)) {
      this.isShowTransfer = false
    }
  }

  private transferFun () { // 转接popover
    this.isShowTransfer = true
    const actionData = { url: '/im-center/action/webchat/getPeerAndOnlineAgents', method: 'POST', data: {} }
    WebchatModule.webchatCommonAction(actionData).then(res => {
      if (res && res.success && res.peerAndOnlineAgents) {
        this.peerAndOnlineAgents = res.peerAndOnlineAgents
      }
    })
  }

  private refreshTransfer () { // 刷新转接数据
    const actionData = { url: '/im-center/action/webchat/getPeerAndOnlineAgents', method: 'POST', data: {} }
    WebchatModule.webchatCommonAction(actionData).then(res => {
      if (res && res.success && res.peerAndOnlineAgents) {
        this.peerAndOnlineAgents = res.peerAndOnlineAgents
      }
    })
  }

  @Watch('$route')
  private routeChange (to: any, from: any) {
    this.isShowTransfer = false
    const routeArr = to.path.split('/')
    if (routeArr[1] === 'im_workBench' && routeArr.length > 4 && routeArr[4] !== 'empty') { // 会话切换会话时长重新计算
      this.timingInterval()
    }
  }

  private startTimer (countTimer: any) {
    let minute: any
    let hour: any
    countTimer = 1 + parseInt(countTimer, 10)
    hour = countTimer / 3600
    hour = parseInt(hour, 10)
    minute = (countTimer % 3600) / 60
    minute = parseInt(minute, 10)
    const second = (countTimer % 3600) % 60
    let mtime = (hour < 10) ? '0' + hour : hour
    mtime += ':'
    mtime += (minute < 10) ? '0' + minute : minute
    mtime += ':'
    mtime += (second < 10) ? '0' + second : second
    return mtime
  }

  private timingInterval () { // 正计时
    const manualTimestamp = deepClone(this.webchatInfo && this.webchatInfo.manualTimestamp) || 0
    const convertManualTimestamp = deepClone(this.webchatInfo && this.webchatInfo.convertManualTimestamp) || 0
    if (this.webchatTimer !== null && this.type === 'webchat_todo') {
      this.currentTime = new Date().getTime() + this.diffTime - manualTimestamp
      this.currentTime = Math.round((this.currentTime / 1000) || 0)
      window.clearInterval(this.webchatTimer)
      this.webchatTimer = window.setInterval(() => {
        this.timing = this.startTimer(this.currentTime)
        this.currentTime = this.currentTime - 0 + 1
      }, 1000)
    } else if (this.webchatTimer !== null && this.type === 'webchat_queue') {
      this.currentTime = new Date().getTime() + this.diffTime - convertManualTimestamp
      this.currentTime = Math.round((this.currentTime / 1000) || 0)
      window.clearInterval(this.webchatTimer)
      this.webchatTimer = window.setInterval(() => {
        this.timing = this.startTimer(this.currentTime)
        this.currentTime = this.currentTime - 0 + 1
      }, 1000)
    } else {
      window.clearInterval(this.webchatTimer)
      if (this.webchatInfo.endTimestamp) {
        const endTimestamp = deepClone(this.webchatInfo.endTimestamp) || this.$store.state.webchat.webchatInfo[this.$route.path.split('/')[4]].endTimestamp
        this.timing = this.startTimer(Math.round(((endTimestamp - manualTimestamp) / 1000) || 0))
      }
    }
  }

  // 获取当前质检记录状态
  get getQtestingStatus () {
    let qtStatus: string
    if (this.webchatInfo.qualityTime) {
      qtStatus = 'scored'
    } else {
      if (this.webchatInfo.applyQualityTime) {
        qtStatus = 'submitted'
      } else {
        qtStatus = 'notsubmitted'
      }
    }
    return qtStatus
  }

  private getQtText () {
    const qtStatus = this.getQtestingStatus
    if (qtStatus === 'scored') {
      return '已评分'
    } else if (qtStatus === 'submitted') {
      return '撤销质检'
    } else {
      return '提交质检'
    }
  }

  private getQtIcon () {
    const qtStatus = this.getQtestingStatus
    if (qtStatus === 'scored') {
      return 'V7_iconV7tubiao_yitijiaozhijianbingpingfen'
    } else if (qtStatus === 'submitted') {
      return 'V7_iconV7tubiao_yitijiaozhijianweipingfen'
    } else {
      return 'V7_iconV7tubiao_weitijiaozhijian'
    }
  }

  private handleQualitytesting () {
    const currentId: string = this.webchatInfo._id
    const submitStatus = this.getQtestingStatus
    if (submitStatus === 'submitted') {
      this.cancelQualitytesting([currentId])
    } else if (submitStatus === 'notsubmitted') {
      if (this.webchatInfo.status !== 'finish') {
        this.$message.error('当前会话还未结束，无法提交！')
        return false
      }
      if (this.webchatInfo.agentReplyMessageCount === 0) {
        this.$message.error('座席消息数为0，无法提交！')
        return false
      }
      if (this.webchatInfo.userId !== (this.$store.state.common.session.user as any)._id) {
        this.$message.error('座席只能处理本人已结束会话')
        return false
      }
      this.submitQualitytesting([currentId])
    } else {
      console.log('已评分')
      return false
    }
  }

  private updateSqStatus (status) {
    if (status === 'submitted') {
      this.$set(this.webchatInfo, 'applyQualityTime', true)
    } else if (status === 'notsubmitted') {
      this.$set(this.webchatInfo, 'applyQualityTime', false)
    }
  }

  private submitQualitytesting (ids) {
    this.$confirm('提交后您的会话将纳入绩效考核，请确认是否提交！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const url = '/im-center/action/quality/applyQuality'
      const sendData = { _ids: ids }
      const actionData = { url, method: 'POST', data: sendData }
      WebchatModule.webchatCommonAction(actionData).then((res: any) => {
        if (res.success) {
          this.$message.success('会话提交成功')
          this.updateSqStatus('submitted')
        }
      })
    }).catch(() => {
      this.$message.warning('会话提交已取消')
    })
  }

  private cancelQualitytesting (ids) {
    this.$confirm('撤回后，该会话将不会纳入绩效考核，请确认是否撤回！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const url = '/im-center/action/quality/undoApplyQuality'
      const sendData = { _ids: ids }
      const actionData = { url, method: 'POST', data: sendData }
      WebchatModule.webchatCommonAction(actionData).then((res: any) => {
        if (res.success) {
          this.updateSqStatus('notsubmitted')
          this.$message.success('会话撤回成功')
        }
      })
    }).catch(() => {
      this.$message.warning('会话撤回已取消')
    })
  }

  private mounted () {
    this.$bus.$on('renderWebchatSummary', () => {
      this.timingInterval()
    })
    document.addEventListener('click', this.transferPopFun)
  }

  private beforeDestroy () {
    window.clearInterval(this.webchatTimer)
    this.$bus.$off('renderWebchatSummary')
    document.removeEventListener('click', this.transferPopFun)
  }
}
</script>
<style lang="stylus" scoped>
.webchatHeadBox
  height 56px
  box-shadow 0px 1px 7px 0px rgba(157,164,173,0.2)
  border-radius 10px 0px 0px 0px
  line-height 26px
  padding 2px 15px 5px 16px
  .title
    width calc(100% - 200px)
    .name
      white-space nowrap
      overflow hidden
      text-overflow ellipsis
      vertical-align middle
      margin-right 10px
      display inline-block
      font-weight 600
      font-size 14px
  .V7_iconfont
    color #A6A6AE
    font-size 12px
    vertical-align middle
  .webchatTime
    vertical-align middle
    color #686e84
  .V7_iconV7tubiao_tuichu, .V7_iconV7tubiao_yichuli
    cursor pointer
    padding-top 13px
  .transfer
    cursor pointer
    margin-right 20px
    padding-top 13px
</style>
